package com.collection;

import lombok.AllArgsConstructor;
import lombok.Data;
import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName CollectionTest
 * @Date 2021/9/22 16:57
 * @Author 李明杰
 * @Description
 */


public class CollectionTest {

    //---------------toMap()测试
    @Test
    public void toMap() {

        @Data
        @AllArgsConstructor
        class Person {
            private String name;
            private String phoneNumber;
            // getters and setters
        }

        List<Person> bookList = new ArrayList<>();
        bookList.add(new Person("jack", "18163138123"));
        bookList.add(new Person("martin", null));
// 空指针异常
        bookList.stream().collect(Collectors.toMap(Person::getName, Person::getPhoneNumber));

    }

    //-----------------集合遍历------------
    @Test
    public void listIter() {
        List<Integer> list = new ArrayList<>();

        for (int i = 1; i <= 10; ++i) {
            list.add(i);
        }
        list.removeIf(filter -> filter % 2 == 0); /* 删除list中的所有偶数 */
        System.out.println(list); /* [1, 3, 5, 7, 9] */
    }


    //    -------------集合转数组测试------------
    @Test
    public void toArray() {
        String[] s = new String[]{
                "dog", "lazy", "a", "over", "jumps", "fox", "brown", "quick", "A"
        };
        List<String> list = Arrays.asList(s);
        Collections.reverse(list);
        //没有指定类型的话会报错
//        s = list.toArray(new String[0]);

        System.out.println(Arrays.toString(s));

    }


    //    -------------------asList()测试------------------
    @Test
    public void asList() {
        Integer[] myArray = {1, 2, 3};
        List myList = Arrays.asList(myArray);

        System.out.println(myList.size());//1
        System.out.println(myList.get(0));//数组地址值
        System.out.println(myList.get(1));//报错：ArrayIndexOutOfBoundsException
//        int[] array = (int[]) myList.get(0);
//        System.out.println(array[0]);//1
    }

    @Test
    public void asList2() {
        List list = new ArrayList<>(Arrays.asList(1, 2, 3));
        list.add(5);
        list.remove(0);
        System.out.println(list);
    }
}
